<template>
	<div class="content">
		<p class="front-tip"> 拍摄您的身份证原件，请确保图片清晰、四角完整。</p>
		<div class="card">
			<div class="front-conn">
				<div class="f90 img-conn front-img" @click="chooseImageFront">
					<img v-if="frontUrl" :src="frontUrl" :class="frontUrl ? papersType=='其他'&&rota1? 'full imgWH' :'full':'none'" @load="loadSuccess" />
				</div>
				<p class="tip" @click="chooseImageFront">{{papersType=='其他'?'上传身份证件照片本人页一':'上传二代身份证人像面照片'}}</p>
			</div>
		</div>
		<div class="card">
			<div class="back-conn mg-t0">
				<div class="f90 img-conn back-img" @click="chooseImageBack">
					<van-image v-if="backUrl" :src="backUrl" alt="上传国徽面照片" :class="backUrl ? papersType=='其他'&&rota2? 'full imgWH' :'full':'none'" @load="loadSuccess" />
				</div>
				<p class="tip" @click="chooseImageBack">{{papersType=='其他'?'上传身份证件照片本人页二 (如有)':'上传二代身份证背面照片'}}</p>
			</div>
		</div>
		<p class="back-tip"> 为了保证远程面签顺利进行，请确保手机网络通畅，并处于相对安静及明亮的环境。 </p>
		<van-button type="info" class="btn" @click="submit"> 下一步</van-button>

		<van-overlay :show="showpopup" class="infor-poup-wap">
      <div class="wrapper" @click.stop>
        <div class="over-wrapp">
          <div class="van-dialog_title">视频须知</div>
          <pre>{{message}}</pre>
				  <div v-if="!showbtn" class="van-dialog__footer1">阅读确定时间（{{timeNum}}s）</div>
				  <div v-else class="van-dialog__footer1">
				  	<div class="uni-dialog-button" @click="getUserInfo">同意</div>
				  	<div class="uni-dialog-button no-button-color" @click="onClose">拒绝</div>
				  </div>
        </div>
      </div>
		</van-overlay>

    <!-- 用来调用拍照功能的隐藏按钮 -->
    <div v-show="false" ref="input" class="input">
      <input id="imageId" type="file" accept="image/*" capture="environment">
      <input id="fileId" type="file" accept="image/*">
    </div>
    <!-- 弹窗提示相册还是相机 -->
    <van-action-sheet
        v-model="showsheet"
        :actions="actions"
        @select="onSelect"
        cancel-text="取消"
        close-on-click-action
    />
	</div>
</template>

<script>
import { mapState } from "vuex"
import { Toast } from 'vant';

	export default {
    name: "wechatOrc",
		data() {
			return {
        showsheet: false,
        actions: [
          { name: '拍照' },
          { name: '相册' },
        ],
				cancelText: ' ',
				confirmText: ' ',
				rota1: false,
				rota2: false,
        showpopup: false,
				// 头像地址
				frontUrl: null,
				// 国徽地址
				backUrl: null,
				// 证件信息数据对象；
				creditcardInfo: {},
				// 客户信息正面
				userInfoFace: {},
				// 客户信息反面
				userInfoBack: {},
				BackOrFront: '',
				papersType: '二代身份证 ',
				show: false,
				showbtn: false,
				timeNum: 5, 
				timei: null,
				message: `请您注意：
				
				1. 请确保在网络通畅且安静的环境下进行本次远程双录。
		
				2. 您即将进入远程录音录像流程，本次销售过程关键环节的录音录像将在事先获得您许可的前提下，通过远程服务渠道方式予以记录，请您适当调整设备摄像头与您本人的相对距离和位置以便于摄像头能够清晰拍摄您的面部。一旦进入双录流程，请勿中途离开或退出双录界面，退出后销售流程将被中止。若您遇到特殊情况，需要中途移动或离席，请您及时告知。
				
				若您同意，请点击“同意”按钮进入双录流程。`
			}
		},
    computed: {
      ...mapState({
        globalData: state => state.globalData
      })
    },
		created() {
			if (this.$route.query &&  this.$route.query.papersType) {
				this.papersType =  this.$route.query.papersType || "二代身份证";
			}
		},
		mounted() {
      this.$nextTick(() => {
        let imageIdinput = document.getElementById("imageId");
        imageIdinput.onchange = (event) => {
          let file2 = event.target.files[0];
          //上传方法
          this.uploadAPI(file2)
        }
        let fileIdinput = document.getElementById("fileId");
        fileIdinput.onchange = (event) => {
          let file1 = event.target.files[0];
          //上传方法
          this.uploadAPI(file1)
        }

      })
		},
		methods: {
			uploadAPI(file) {
				console.log('上传接口', file)
        if (!file) return false;
				let _that = this;
				let reader = new FileReader();
				reader.readAsDataURL(file);
				reader.onload = function(result){
					console.log(result,"resultresult");
					_that.upLoadImg(result.target.result, _that.BackOrFront)
				}
			},
			showready() {
				this.show = true
				this.showpopup = true
				this.timei= setInterval(()=>{
					this.timeNum = this.timeNum - 1;
					if (this.timeNum == 0) {
						clearInterval(this.timei)
						this.showbtn = true
						this.cancelText = "拒绝";
						this.confirmText = "同意";
					}
				}, 1000)
			},
			getUserInfo() {
        this.showpopup = false
				this.show = false;
				this.timeNum = 5;
				this.showbtn = false;
				this.cancelText = " ";
				this.confirmText = " ";
				this.submitCardInfo();
			},
		
			submitCardInfo () {
				const { bankCode, reserveId } = this.globalData;
		
				const roomNum = `${bankCode}${reserveId}`;
				// const roomNum = `${'0322'}${'001'}`;
        this.$store.commit("UPDATE_GLOBAL", {key: "roomNum", val:  roomNum});
				console.log('-------房间号--------', roomNum);

				setTimeout(() => {
					this.$router.replace(`/videoRoom?roomNum=${roomNum}`);
				}, 300);
			},
			onClose() {
				this.showbtn = false;
				this.showpopup = false;
				this.cancelText = " ";
				this.confirmText = " ";
				this.show = false;
				this.timeNum = 5;
			},
			// 选择人像面
			chooseImageFront() {
				this.BackOrFront = 'face';
				this.setShowActionSheet()
			},
      onSelect(item) {
        if (item.name) {
          console.log(item.name);
          this.chooseImage(item.name)
        }
      },
			setShowActionSheet() {
        this.showsheet = true;
			},
			chooseImage(tapIndex) {
				console.log(this.BackOrFront,'this.BackOrFront');
				if (tapIndex=='拍照') {
          return document.getElementById("imageId").click();
					return false
				} else {
					return document.getElementById("fileId").click();
				}
			},
			// 选择国徽面
			chooseImageBack() {
				this.BackOrFront = 'nation';
				this.setShowActionSheet()
			},
			upLoadImg(res, type) {
				console.log(type);
					let _that = this
					let strFile = (typeof res == 'string') ? res : res.data || "";
					const { bankCode, meetingNum } = this.globalData;
					const { papersType } = this;
					
					let strFileList = strFile.split(',')
					
					let newstrFile = strFileList[strFileList.length-1]
					
					let obj = {
						direction: type,
						file: newstrFile,
						bankCode: bankCode,
						meetingNum: meetingNum|| '949047',
						instCode: '',
						openId: '',
						papersType: papersType || "二代身份证"
					}
					console.log(obj, "objobjobj");
          Toast.loading({ duration: 0, forbidClick: true, message: '图片解析中' });
          this.$getAPIs(this, obj, "上传证件并ocr","apis", "uploadeIdcard").then( succ => {
            Toast.clear();
						if (!succ || !succ.success || succ.status != 0) {
              Toast.fail(succ.msg || "上传失败！");
							return _that.resetImageUrl(type);
						}
						let checkResult = _that.checkOcrResult(type, succ.content)
						if (checkResult  && papersType == '二代身份证' ) {
              Toast.fail(`未识别到${checkResult}，请重新拍摄`);
							if (type == 'face') {
								_that.frontUrl = '';								
								_that.userInfoFace = {};
							}
							if (type == 'nation') {
								_that.backUrl = '';								
								_that.userInfoBack = {};
							}
						} else {
							if (type == 'face') {
								_that.frontUrl = _that.getBase64ImageUrl(succ.content.faceImg);
								_that.userInfoFace = succ.content;
							}
							if (type == 'nation') {
								_that.backUrl = _that.getBase64ImageUrl(succ.content.nationImg);								
								_that.userInfoBack = succ.content;
							}
						}
					}, (err) => {
            Toast.clear();
						_that.resetImageUrl(type)
					}).finally(() => {
						// 你的代码
						setTimeout(()=>{
              Toast.clear();
            },300)
					});
			},
			checkOcrResult(type, result) {
				let checkResult = '';
				if (type === 'face') {
					// 检查所有人像面字段
					const faceCheckItem = [{
							key: 'name',
							tip: '姓名'
						},
						{
							key: 'sex',
							tip: '性别'
						},
						{
							key: 'people',
							tip: '民族'
						},
						{
							key: 'address',
							tip: '住址'
						},
						{
							key: 'birthday',
							tip: '出生年月'
						},
						{
							key: 'custId',
							tip: '证件号'
						},
					]
					faceCheckItem.some(item => {
						if (!result[item.key]) {
							checkResult = item.tip;
							return true;
						}
					})
				} else {
					// 检查所有国徽面字段
					const nationCheckItem = [{
							key: 'issueAuthority',
							tip: '签发机关'
						},
						{
							key: 'startValidityPeriod',
							tip: '签发时间'
						},
						{
							key: 'validityPeriod',
							tip: '有效期限'
						},
					]
					nationCheckItem.some(item => {
						if (!result[item.key]) {
							checkResult = item.tip;
							return true;
						}
					})
				}
				return checkResult;
			},
		
			getBase64ImageUrl: function (data) {
				var base64Data = data;
				const base64ImgUrl = "data:image/png;base64," + base64Data;
				return base64ImgUrl;
			},
		
			resetImageUrl(type) {
				let _that = this;
        Toast.fail(`图片解析失败请重新上传`);
				if (type == 'face') {
					_that.frontUrl = '';		
				}
				if (type == 'nation') {
					_that.backUrl = '';		
				}
			},
		
			// 点击上传图片按钮
			async submit() {
				if (!this.frontUrl) {
          Toast.fail(`请上传身份证人像面照片`);
					return;
				}
				if (!this.backUrl && this.papersType=='二代身份证') {
          Toast.fail(`请上传身份证国徽面照片`);
					return;
				}
				this.showready()
			},
			loadSuccess(e){
				const {BackOrFront} = this;
        // console.log(e, e.target, e.target.naturalWidth, e.target.naturalHeight)
        const width = e.target.naturalWidth
        const height = e.target.naturalHeight
				if (width < height) {
					if (BackOrFront == 'face') {
						this.rota1 = true;
					} else {
						this.rota2 = true;
					}
				} else {
					if (BackOrFront == 'face') {
						this.rota1 = false;
					} else {
						this.rota2 = false;
					}
				}
			}
		}
	}
</script>

<style>
.content {
  display: flex;
  flex-flow: column nowrap;
  justify-content: space-between;
  align-items: center;
  flex: 1;
  background: #f5f5f5;
}

.mg-t0 {
  margin-top: 0;
}

.img-conn {
  width: 280px;
  height: 178px;
  justify-content: center;
  display: flex;
  align-items: center;
  background-repeat: no-repeat;
  background-size: contain;
  background-position: center;
}

.front-img {
  background-image: url('');
}

.back-img {
  background-image: url('');
}

.f90 {
  flex: 0 1 auto;
}

.front-tip {
  display: flex;
  color: #9a9a9a;
  font-size: 12px;
  justify-content: left;
  align-self: flex-start;
  padding: 0 20px;
  margin-bottom: 5px;
}

.back-tip{
  display: flex;
  color: #9a9a9a;
  font-size: 12px;
  justify-content: left;
  align-self: flex-start;
  padding: 0 20px;
  margin-bottom: 10px;
}

.card {
  display: flex;
  flex: 0 1 40%;
}

.front-conn, .back-conn {
  display: flex;
  flex: auto;
  flex-flow: column nowrap;
}

.front-conn {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.back-conn {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.tip {
  color: #a6a6a6;
  font-size: 15px;
  text-align: center;
  padding: 7px;
}

.none {
  display: none;
}

.full {
  width: 100%;
  height: 100%;
  display: inline-block;
  overflow: hidden;
}

.imgWH {
  height: 280px;
  width: 175px;
  transform: rotateZ(-90deg);
}
.btn {
  width: 100%;
  font-weight: 500;
  border-radius: 0;
  margin: 0;
  padding: 0;
  height: 60px;
  line-height: 60px;
}

.wrapper{
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.over-wrapp{
  border-radius: 30px;
  width: 300px;
  max-height: 75vh;
  background: #FFFFFF;
}
pre {
  white-space: pre-line;
  word-wrap: break-word;
  padding: 20px;
  text-align: left;
  margin: 0;
  font-size: 14px;
  color: #6c6c6c;
}

.van-dialog_title{
  display: flex;
  flex-direction: row;
  justify-content: center;
  padding-top: 25px;
  font-size: 16px;
  color: #0473EA;
  font-weight: 500;
}
.van-dialog__footer1 {
	line-height: 92px;
  width: 100%;
  font-size: 14px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #0473EA;
}
.uni-dialog-button {
  line-height: 45px;
  height: 45px;
  width: 100%;
  font-size: 16px;
  border-top: 1px solid #f5f5f5;
}
.no-button-color{
  color: #333333;
}
</style>
